
//
//  DataHelper.m
//  Travel assistant
//
//  Created by 王京 on 16/3/2.
//  Copyright © 2016年 旅游助手. All rights reserved.
//

#import "DataHelper.h"
#import "Find.h"
static DataHelper *helper = nil;

@interface DataHelper ()



@end

@implementation DataHelper

+ (DataHelper *)shareHelper{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (helper == nil) {
            helper = [[DataHelper alloc]init];
        }
    });
    return helper;
}

- (void) requestURL:(NSString *)urlString tableView:(SUCCESS)tableViewBlock{
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        self.dataArray = [NSMutableArray array];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        
        for (NSDictionary *d in dict[@"response"]) {
            
            Find *fd = [[Find alloc]init];
            
            [fd setValuesForKeysWithDictionary:d];
            NSLog(@"---------------%@",fd.url);
            [self.dataArray addObject:fd];
            
            NSLog(@"%@",fd);
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            tableViewBlock(self.dataArray);
        });
        
    }];
    
    [task resume];
    
}

-(void)requestURL:(NSInteger)number t:(SUCCESS)backBlock{
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://travelbox-interface.xyz.cn/advertisement/get?sig=f15f52bf5e42d19542682c8487eefaf2&ts=1456899648920&uid=suitcase&pageNo=%ld",number]];
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        self.dataArray = [NSMutableArray array];
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        
        for (NSDictionary *d in dict[@"response"]) {
            
            Find *fd = [[Find alloc]init];
            
            [fd setValuesForKeysWithDictionary:d];
            NSLog(@"---------------%@",fd.url);
            [self.dataArray addObject:fd];
            
            NSLog(@"%@",fd);
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            backBlock(self.dataArray);
        });
        
    }];
    
    [task resume];
    
    
    
}

@end
